package jee.boot.common.utils;

import jee.boot.common.basic.ServiceException;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @version 2017-04-23.
 * @auth Licw
 */
public class ObjectUtils {
    private static Logger logger= LoggerFactory.getLogger(ObjectUtils.class);
    /**
     * 通过序列化接口深拷贝对象
     *
     * @param obj
     * @param <T>
     * @return
     */
    public static <T extends Serializable> T cloneSerializable(T obj) {
        ByteArrayOutputStream memoryBuffer = new ByteArrayOutputStream();
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        T dest = null;
        try {
            out = new ObjectOutputStream(memoryBuffer);
            out.writeObject(obj);
            out.flush();
            in = new ObjectInputStream(new ByteArrayInputStream(memoryBuffer.toByteArray()));
            dest = (T) in.readObject();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            throw new ServiceException();
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
        return dest;
    }



}
